<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :sm="24" :lg="12">
        <el-card class="filter-container">
          <el-row>
            <bar-chart :chart-data="currentBillStat" title="当前支出" />
          </el-row>
        </el-card>
      </el-col>
      <el-col :sm="24" :lg="12">
        <el-card class="filter-container">
          <el-row>
            <year-bar-chart />
          </el-row>
        </el-card>

      </el-col>
    </el-row>

    <el-card class="filter-container">
      <div>
        <i class="el-icon-search" />
        <span>筛选</span>
        <div class="filter-btn">
          <el-button
            icon="el-icon-search"
            type="primary"
            size="small"
            @click="handleSearchList()"
          >
            查询
          </el-button>
          <el-button
            icon="el-icon-setting"
            size="small"
            @click="handleResetSearch()"
          >
            重置
          </el-button>

          <el-button
            class="btn-add"
            type="success"
            size="mini"
            icon="el-icon-plus"
            @click="add"
          >
            添加
          </el-button>
        </div>
      </div>
      <div style="margin-top: 25px">
        <el-form :inline="true" :model="listQuery" size="small">
          <el-row>
            <el-col :sm="12" :lg="6">
              <el-form-item label="选择时间：">
                <el-date-picker
                  v-model="queryMonth"
                  clearable
                  type="month"
                  placeholder="选择时间"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <el-card class="table-container">

      <el-timeline>
        <el-timeline-item v-for="(item, index) in dateBillList" :key="index" :timestamp="item.date" placement="top">
          <el-row :gutter="24">
            <el-col v-for="(bill, billIndex) in item.bills" :key="billIndex" :span="4">
              <el-card>
                <div class="box-card-header">
                  <svg-icon :icon-class="bill.iconClass" class-name="disabled" />
                  <span class="worth-text">{{ bill.type === 1 ? '-' : '' }} ¥{{ bill.worth | centToYuan }}</span>
                </div>
                <div style="padding: 14px;">
                  <div class="bottom">
                    <el-button size="small" type="warning" @click="update(bill)">编辑</el-button>
                    <el-button size="small" type="danger" @click="remove(bill)">删除</el-button>
                  </div>

                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-timeline-item>
      </el-timeline>

      <empty v-if="dateBillList.length === 0" />
    </el-card>

    <el-dialog
      :title="isAdd ? '新增账单' : '编辑账单'"
      :visible.sync="editOperFormVisible"
      center
      width="30%"
    >
      <el-form
        ref="editOperForm"
        :rules="editOperFormRules"
        :model="editOperForm"
      >
        <el-form-item label="日期：">
          <el-date-picker
            v-model="editOperForm.date"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="收支：" prop="type">
          <el-radio-group v-model="editOperForm.type">
            <el-radio-button label="1">支出</el-radio-button>
            <el-radio-button label="0">收入</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称：" prop="name">
          <el-input
            v-model="editOperForm.name"
            placeholder="名称"
          />
        </el-form-item>
        <el-form-item label="金额：" prop="worth">
          <el-input v-model="editOperForm.worth" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editOperFormVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import {
  getList,
  create,
  updateById,
  removeById
} from '@/api/invest/bill'

import BarChart from './components/BarChart'
import YearBarChart from './components/YearBarChart'

import { fillTime, centToYuan } from '@/utils'

const defaultEditForm = {
}

const defaultListQuery = {
  sorts: '-date'
}

import Empty from '@/components/Empty'

export default {
  components: {
    Empty,
    BarChart,
    YearBarChart
  },
  data() {
    return {
      queryMonth: null,

      listQuery: Object.assign({}, defaultListQuery),
      dateBillList: [],
      total: 0,

      statusOptions: [{
        value: 1,
        label: '启用'
      }, {
        value: 0,
        label: '禁用'
      }],

      listLoading: true,
      loading: false,

      isAdd: false,
      editOperFormVisible: false,
      editOperForm: {},
      editOperFormRules: {
        name: [{ required: true, trigger: 'blur', message: '请填写名称' }],
        worth: [{ required: true, trigger: 'blur', message: '缺少金额' }],
        type: [{ required: true, trigger: 'blur', message: '请选择类型' }]
      },

      currentBillStat: [],
      yearBillStat: []
    }
  },
  watch: {
    queryMonth: function(newValue) {
      const year = newValue.getFullYear()
      const month = newValue.getMonth() + 1

      this.listQuery.startDate = year + '-' + fillTime(month) + '-' + '01'
      this.listQuery.endDate = year + '-' + fillTime(month) + '-' + new Date(year, month, 0).getDate()

      this.getList()
    }
  },
  mounted() {
    this.initListQuery()
  },
  methods: {
    initListQuery() {
      this.queryMonth = new Date()
    },
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        const data = response.data
        this.dateBillList = data

        const currentBillStat = [0, 0]
        data.map(dateData => {
          dateData.bills.map(bill => {
            const type = bill.type
            const worth = bill.worth

            if (type === 0) {
              currentBillStat[1] += worth
            } else if (type === 1) {
              currentBillStat[0] += worth
            }
          })
        })

        this.currentBillStat = [centToYuan(currentBillStat[0]), centToYuan(currentBillStat[1])]
        console.log(currentBillStat)

        this.listLoading = false
      })
    },
    handleSearchList() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleResetSearch() {
      this.listQuery = {}
    },
    add() {
      this.isAdd = true
      this.editOperForm = Object.assign({}, defaultEditForm)
      this.editOperFormVisible = true
    },
    update(row) {
      this.isAdd = false
      this.editOperForm = Object.assign({}, row)
      this.editOperForm.worth = centToYuan(row.worth)
      this.editOperFormVisible = true
    },
    handleSave() {
      this.$refs.editOperForm.validate(valid => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const params = Object.assign({}, this.editOperForm)
            params.worth = params.worth * 100
            if (this.isAdd) {
              create(params).then(_ => {
                this.$message.success('新建账单成功！')
                this.editOperFormVisible = false
                this.getList()
              })
            } else {
              updateById(params.id, params).then(_ => {
                this.$message.success('修改账单成功！')
                this.editOperFormVisible = false
                this.getList()
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    remove(row) {
      this.$confirm('是否要删除账单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeById(row.id).then(_ => {
          this.getList()
        })
      })
    }
  }
}
</script>

<style scoped>

.disabled {
  pointer-events: none;
}

.box-card-header{
  font-size:18px;
}

.worth-text{
  margin-left:8px;
}

</style>
